<template>
  <div class="afternoon-tea">
    <el-form inline :model="paramsForm" ref="paramsForm" class="filter">
      <el-form-item label="后台单号">
        <el-input
          class="w-180"
          v-model.trim="paramsForm.xmbzNo"
          clearable
          placeholder="后台单号"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="总仓">
        <el-select
          ref="mainWarehouseRef"
          v-model="paramsForm.mainWarehouse"
          placeholder="总仓"
          size="small"
          @change="barnchWarehouses"
          class="w-100"
        >
          <el-option
            v-for="(mainWareHouse, index) in getMainWarehouseList"
            :key="index"
            :label="mainWareHouse.deptName"
            :value="mainWareHouse.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分仓" class="branchWareHouse">
        <el-select
          ref="barnchWarehousesRef"
          v-model="paramsForm.warehouseId"
          placeholder="分仓"
          size="small"
          class="w-100"
        >
          <el-option
            v-for="item in getSeparateWarehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select
          ref="statusRef"
          v-model="paramsForm.status"
          placeholder="全部"
          size="small"
          class="w-100"
        >
          <el-option
            v-for="item in statusList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打印状态">
        <el-select
          ref="printingRef"
          v-model="paramsForm.printingState"
          placeholder="全部"
          class="w-100"
          size="small"
        >
          <el-option
            v-for="item in printingStateList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送时间">
        <el-form-item style="display: flex;">
          <el-date-picker
            v-model="paramsForm.timeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm"
            :default-time="['00:00:00', '23:59:59']"
            format="yyyy-MM-dd HH:mm"
            :clearable="false"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input
          class="w-180"
          ref="goodsNameRef"
          v-model="paramsForm.goodsName"
          placeholder="产品名称"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          type="primary"
          size="small"
          plain
          @click="onSearch()"
          >查询</el-button
        >
      </el-form-item>
    </el-form>

    <div class="main">
      <div>
        <el-checkbox v-model="checkedAll" @change="onCheckall">全选</el-checkbox>
        <el-button type="primary" size="small" @click="onBatchProd">批量生产</el-button>
        <!-- <el-button type="primary" size="small" @click="onBatchPrint" data-btn-type="print">批量打印</el-button> -->
        <el-button type="primary" size="small" @click="onAbnormalOrder">异常订单</el-button>
        <el-checkbox
          v-model="isNeedIngredient"
          label="是否打印配料表"
          border
          size="small"
          class="mlr-5"
          @change="onIsNeedIngredientChange"
        ></el-checkbox>
        <el-checkbox
          v-model="isOpenAutoFetch"
          label="开启自动刷单"
          border
          size="small"
          class="mlr-5"
          @change="onisOpenAutoFetchChange"
        ></el-checkbox>
        <el-checkbox
          v-model="isOpenPrintPreview"
          label="开启打印预览"
          border
          size="small"
          class="mlr-5"
        ></el-checkbox>
        <!-- <el-button type="danger" size="small" @click="closeOrder">关闭接单</el-button>
        <el-button type="danger" size="small" plain @click="onCloseOrderList">接单关闭列表</el-button> -->
      </div>

      <div>
        <template v-if="orderList && orderList.length">
          <orderItem v-for="item in orderList" :key="item.id" :orderData="item" @onFetch="fetchList" @onPrint="handlePrint"></orderItem>
          <el-pagination
            background
            :current-page.sync="pageParams.currentPage"
            layout="prev, pager, next, sizes, total"
            :page-sizes="[5, 10, 15, 20]"
            :page-size.sync="pageParams.pageSize"
            :total="pageParams.total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            class="mt-10 mb-20"
          >
          </el-pagination>
        </template>
        <XmEmpty v-else description="暂无数据"></XmEmpty>
      </div>
    </div>

    <print ref="print" @printed="fetchList"></print>

    <abnormalOrderDialog ref="abnormalOrderDialog" :mainWarehouseId="paramsForm.mainWarehouse" :warehouseId="paramsForm.warehouseId"></abnormalOrderDialog>
    <!-- <closeOrderListDialog ref="closeOrderListDialog"></closeOrderListDialog> -->
  </div>
</template>

<script>
import {
  getMainWarehouseListByRoleIdAll, // 总仓
  getSeparateWarehouseListByRoleIdAll // 分仓
} from "@/api/createOrder";
import {
  getProductionQueryPage, //查询列表
  batchTeaStartProduction,
} from "@/api/scheduling/prodManage";
import orderItem from "./orderItem";
import abnormalOrderDialog from '../../components/abnormalOrderDialog'
import closeOrderListDialog from '../../components/closeOrderListDialog'
import print from './print'
const statusList = [
  {
    dictKey: 0,
    dictValue: "全部"
  },
  {
    dictKey: 2,
    dictValue: "待生产"
  },
  {
    dictKey: 3,
    dictValue: "生产中"
  },
  {
    dictKey: 4,
    dictValue: "已入库"
  },
  {
    dictKey: 10,
    dictValue: "已退订"
  },
  {
    dictKey: 9,
    dictValue: "改期"
  }
];
const printingStateList = [
  {
    dictKey: 0,
    dictValue: "全部"
  },
  {
    dictKey: 1,
    dictValue: "未打印"
  },
  {
    dictKey: 2,
    dictValue: "已打印"
  }
];
export default {
  data() {
    const isNeedIngredient =  JSON.parse(window.localStorage.getItem('afternoonTea-isNeedIngredient')) || false
    return {
      isNeedIngredient: isNeedIngredient,
      isOpenAutoFetch: false,
      isOpenPrintPreview: false,
      paramsForm: {
        deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        xmbzNo: "",
        mainWarehouse: "",
        warehouseId: "",
        status: 0,
        printingState: 0,
        goodsName: "",
        timeValue: [
          this.dayjs(new Date())
            .format("YYYY-MM-DD 00:00:00")
            .toString(),
          this.dayjs(new Date())
            .format("YYYY-MM-DD 23:59:59")
            .toString()
        ]
      },
      pageParams: {
        total: 0,
        pageSize: 10,
        currentPage: 1
      },
      checkedAll: false,
      orderList: [],
      getMainWarehouseList: [],
      getSeparateWarehouseList: [],
      statusList,
      printingStateList,
      pickerOptions: {
        onPick: obj => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate: time => {
          if (this.pickerMinDate) {
            const day1 = 31 * 24 * 3600 * 1000;
            let maxTime = this.pickerMinDate + day1;
            let minTime = this.pickerMinDate - day1;
            return time.getTime() > maxTime || time.getTime() < minTime;
          }
        }
      }
    };
  },
  methods: {
    onSearch() {
      this.fetchList();
    },
    fetchList() {
      const params = this.getParams();
      getProductionQueryPage(params).then(res => {
        this.pageParams.total = res.data.data.total;
        this.orderList = res.data.data.rows;
        this.checkedAll = false;
        this.orderList.forEach(itemorder => {
          this.$set(itemorder, "checked", false);
          if (itemorder.orderDetailVOS && itemorder.orderDetailVOS.length) {
            const itemData = itemorder.orderDetailVOS[0]
            itemorder.productionState = itemData.productionState
            itemorder.productionStateName = itemData.productionStateName
            itemorder.printingTimes = itemData.printingTimes
          }
        });
        if (this.orderList) {
          this.sameGoodsMerge(this.orderList)
        }
      });
    },
    // 将订单相同的商品合并
    sameGoodsMerge(orderList) {
      orderList.forEach(itemorder => {
        if (itemorder.orderDetailVOS && itemorder.orderDetailVOS.length) {
          const goods = []
          itemorder.orderDetailVOS.forEach(item => {
            const findGood = goods.find(g => item.goodsId === g.goodsId)
            if (findGood) {
              findGood.quantity++
              findGood.orderDetailIdList.push(item.id)
            } else {
              item.quantity = 1
              item.orderDetailIdList = [item.id]
              goods.push(item)
            }
          })
          itemorder.orderDetailVOS = goods
        }
      });
    },
    // 列表参数
    getParams() {
      const params = {
        ...this.paramsForm,
        status: this.paramsForm.status || 0,
        printingState: this.paramsForm.printingState || 0,
        deliveryStartTime: this.dayjs(this.paramsForm.timeValue[0]).format('YYYY-MM-DD HH:mm:00'),
        deliveryEndTime: this.dayjs(this.paramsForm.timeValue[1]).format('YYYY-MM-DD HH:mm:59'),
        page: this.pageParams.currentPage,
        size: this.pageParams.pageSize
      };

      if (this.paramsForm.mainWarehouse && this.getMainWarehouseList.length) {
        const house = this.getMainWarehouseList.find(item => item.id == this.paramsForm.mainWarehouse)
        house && (params.mainWarehouse = house.deptName)
      }

      delete params.timeValue
      return params;
    },
    getMinWareList() {
      const cityId = JSON.parse(window.localStorage.getItem("saber-areaId"))
        .content;
      // 总仓
      getMainWarehouseListByRoleIdAll({ parentId: cityId }).then(res => {
        res.data.data.unshift({
          id: "",
          deptName: "全部"
        });
        this.getMainWarehouseList = res.data.data;
      });
    },
    //仓库地区ID选择事件
    barnchWarehouses() {
      this.paramsForm.warehouseId = "";
      const saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
      const cityareaId = saberareaIds["content"];
      getSeparateWarehouseListByRoleIdAll({
        cityId: cityareaId,
        deptId: this.paramsForm.mainWarehouse
      }).then(response => {
        response.data.data.unshift({
          id: "",
          name: "全部"
        });
        this.getSeparateWarehouseList = response.data.data;
        this.paramsForm.warehouseId = response.data.data[0].id;
      });
    },
    handleCurrentChange: function(currentPage) {
      this.pageParams.currentPage = currentPage;
      this.fetchList();
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    handleSizeChange: function(size) {
      this.pageParams.pageSize = size;
      this.fetchList();
    },
    onCheckall(checked) {
      this.orderList.forEach(item => {
        item.checked = checked
      })
    },
    onAbnormalOrder() {
      this.$refs.abnormalOrderDialog.show()
    },
    // 关闭接单
    closeOrder() {
      
    },
    onCloseOrderList() {
      this.$refs.closeOrderListDialog.show()
    },
    onIsNeedIngredientChange() {
      window.localStorage.setItem('afternoonTea-isNeedIngredient', this.isNeedIngredient)
    },
    onisOpenAutoFetchChange(value) {
      this.setAutoFetchTimer(value)
    },
    setAutoFetchTimer(isAuto) {
      if (isAuto) {
        this.autoFetchTimer = setInterval(() => {
          this.fetchList()
        }, 60 * 1000)
      } else {
        window.clearInterval(this.autoFetchTimer)
      }
    },
    // 批量生产
    onBatchProd() {
      const checkedList = this.getCheckedList()
      if (checkedList && checkedList.length) {
        if (checkedList.some(item => item.productionState != 2)) {
          this.$message({
            message: '点击批量生产前，请选择待生产的订单',
            type: 'warning'
          });
          return
        }
        this.$confirm(`确认批量生产所选${checkedList.length}个订单？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchTeaStartProduction({orderIds: checkedList.map(item => item.id)}).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: '批量生产成功',
                message: '请您耐心等待',
                type: 'success'
              })
              this.fetchList()
            }
          })
        })
      } else {
        this.$message({
          message: '您还未选择订单，请先勾选订单',
          type: 'warning'
        });
      }
    },
    // 批量打印
    onBatchPrint() {
      const checkedList = this.getCheckedList()
      if (checkedList && checkedList.length) {
        if (checkedList.some(item => item.productionState != 3 && item.productionState != 4)) {
          this.$message({
            message: '点击批量打印前，请选择生产中或已入库的订单',
            type: 'warning'
          });
          return
        }
        this.$confirm(`确认批量打印所选${checkedList.length}个订单？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.print.print({
            orderList: checkedList,
            isNeedIngredient: this.isNeedIngredient,
            isOpenPrintPreview: this.isOpenPrintPreview
          })
        })
      } else {
        this.$message({
          message: '您还未选择订单，请先勾选订单',
          type: 'warning'
        });
      }
    },
    getCheckedList() {
      const checkedList = this.orderList.filter(item => item.checked)
      return checkedList || []
    },
    async handlePrint({type, orderData}) {
      if (type === 'print') {
        await this.$refs.print.print({
          orderList: [orderData],
          isNeedIngredient: this.isNeedIngredient,
          isOpenPrintPreview: this.isOpenPrintPreview
        })
      } else if (type === 'printOrder') {
        await this.$refs.print.printOrder({
          orderList: [orderData],
          isOpenPrintPreview: this.isOpenPrintPreview
        })
      } else if (type === 'printIngredient') {
        await this.$refs.print.printIngredient({
          orderList: [orderData],
          isOpenPrintPreview: this.isOpenPrintPreview
        })
      }
      this.fetchList()
    }
  },
  mounted() {
    this.getMinWareList();
    this.barnchWarehouses();
    this.fetchList();
  },
  components: {
    orderItem,
    abnormalOrderDialog,
    closeOrderListDialog,
    print
  }
};
</script>
<style lang="scss" scoped>
.afternoon-tea {
  .filter {
    padding: 0 20px;
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  .main {
    // background: #f5f7fa;
    padding: 0px 20px;
  }

}
</style>
